function IsNumeric(sText){
   var ValidChars = "0123456789.";
   var IsNumber=true;
   var Char;
 
   for (i = 0; i < sText.length && IsNumber == true; i++) { 
	   Char = sText.charAt(i); 
	   if (ValidChars.indexOf(Char) == -1){
		   IsNumber = false;
       }
   }
   return IsNumber;
}


function addToBox(event){
    var callid = event.target.id;
    var sno = callid.split('_')[1];
    var toBoxId = 'box_'+sno;
	if(sno=="0"){
		$("#allChoices option:selected").each(function(index){
			var subjNo = $(this).val();
			var optNum = $("#optCnt").val();
			for(var i=0;i<optNum;i++){
				$("#box_"+(i+1)).children().each(function() {
					var optSubjNum = $(this).val();
					if(optSubjNum == subjNo){
						Edushare.FunctionalTextFields.SetError
							('The same course cannot be present as both elective and required course in the same semester');
						return;
					}
				});
			}
		});
		$("#allChoices option:selected").remove().appendTo("#"+toBoxId);
	}
	else{
		var doNotAdd = 0;
		$("#allChoices option:selected").each(function(index){
			var newSubjNum = $(this).val();
			$("#"+toBoxId).children().each(function() {
				var existSubjNum = $(this).val();
				if(newSubjNum == existSubjNum){
					Edushare.FunctionalTextFields.SetError
						('Error : Duplicate course addition');
					event.preventDefault();
					doNotAdd = 1;
					return;
				}
			});
		});
		var htm = $("#allChoices option:selected").clone();
		if(doNotAdd == 0)
			$("#"+toBoxId).append(htm);
	}
    event.preventDefault();
}

function removeFromBox(event){
    var callid = event.target.id;
    var sno = callid.split('_')[1];
    var fromBoxId = 'box_'+sno;
	if(sno=="0")
		$("#"+fromBoxId+" option:selected").remove().appendTo("#allChoices");
	else{
		$("#"+fromBoxId+" option:selected").remove();
	}
    event.preventDefault();
}

function updateString(){
	//Get values of items in box_0 and put it in man:
	var subjString = "man:";
	$("#box_0").children().each(function() {
		subjString += $(this).val();
		subjString +=",";
	});
	subjString = subjString.substring(0,subjString.length-1);
	subjString += ";";
	var optNum = $("#optCnt").val();
	
	for(var i=0;i<optNum;i++){
		subjString += "opt"+i+":";
		$("#box_"+(i+1)).children().each(function() {
			subjString += $(this).val();
			subjString +=",";
		});
		subjString = subjString.substring(0,subjString.length-1);
		subjString += ";";
	}
	$("#hiddenfield").val(subjString);
}

function updateSelectBoxes(){
	//Called at page load. Only adds courses to boxes.
	//Add to mandatory box.
	var subjString = $("#hiddenfield").val();
	var mandatoryCourseList = Edushare.CourseChooser.getMandatoryCourses(subjString);
	for(var i=0;i<mandatoryCourseList.length;i++){
		$("#allChoices option[value='"+ mandatoryCourseList[i] +"']").remove().appendTo("#box_0");
	}
	var optNum = Edushare.CourseChooser.getNumberOptionalSlots(subjString);
	setOptionalBoxes(optNum);
	for(var j=0;j<optNum;j++){
		var optCourseList = 	Edushare.CourseChooser.getCourseChoices(subjString, j);
		for(var k=0;k<optCourseList.length;k++){
			var htm = $("#allChoices option[value='"+ optCourseList[k] +"']").clone();
			$("#box_"+(j+1)).append(htm);
		}
	}	
}

function setOptionalBoxes(opt){
    for(var i=1; i <= opt; i++){
        $("#optSel").append('<div class="transDiv">'+
                    '<button id="add_'+i+'" class="es-button ui-state-default ui-corner-all">&gt;&gt;</button>'+
                    '<br/><br/>'+
                    '<button id="remove_'+i+'" class="es-button ui-state-default ui-corner-all">&lt;&lt;</button>'+
            '</div>'+
            '<div style="width:250px; float:left">'+
                '<p>'+
                '<label><strong>Choices for Elective '+i+'</strong></label><br/>'+
                '<select id="box_'+i+'" multiple size="5" style="width:250px; scroll:no;">'+
                '</select>'+
                '</p>'+
            '</div>');
        
    	$("#add_"+i).click(function(event){
    		addToBox(event);            
        });        
        
    	$("#remove_"+i).click(function(event){
    		removeFromBox(event);
    	});
    }	
}

$(document).ready(function(){
	
	$("#optCnt").val(Edushare.CourseChooser.getNumberOptionalSlots($("#hiddenfield").val()));
	updateSelectBoxes();	
    $("#ccs").click(function(event){
        var opt = $("#optCnt").val();
        if(!IsNumeric(opt)){
        	Edushare.FunctionalTextFields.SetError('Numeric input required for number of elective courses');
        	$("#optCnt").val(0);
        	return;
        }
        $("#optSel").html('');
        setOptionalBoxes(opt);
        event.preventDefault();
    });    
    
    $(".CourseSelectionForm").submit(function(){
    	updateString();
    	var subjString = $("#hiddenfield").val();
    	var electives = Edushare.CourseChooser.getNumberOptionalSlots(subjString);
    	var i;
    	for(i=0;i<electives;i++){
    		var optCourseList = Edushare.CourseChooser.getCourseChoices(subjString, i);
    		if(optCourseList.length<2){
    			Edushare.FunctionalTextFields.SetError('Please select at least two courses for each elective.');
    			return false;
    		}
    	}    	
    	return true;
    });		
    
	$("#add_0").click(function(event){
		addToBox(event);            
    });        
    
	$("#remove_0").click(function(event){
		removeFromBox(event);
	});

});
